<template>
  <div class="api-test-container">
    <h2>API 测试工具（类似 Postman）</h2>

    <!-- 请求方法选择 -->
    <div class="method-url-group">
      <select v-model="method" class="method-select">
        <option value="get">GET</option>
        <option value="post">POST</option>
        <option value="put">PUT</option>
        <option value="delete">DELETE</option>
      </select>

      <!-- URL 输入框 -->
      <input
          v-model="url"
          type="text"
          placeholder="请输入请求的URL（例如：https://jsonplaceholder.typicode.com/posts/1）"
          class="url-input"
      />
    </div>

    <!-- 请求头和请求体 -->
    <div class="input-group">
      <div class="input-section">
        <label>请求头（JSON格式，可选）</label>
        <textarea
            v-model="headers"
            placeholder="例如：{&quot;Content-Type&quot;: &quot;application/json&quot;}"
            class="headers-input"
        ></textarea>
      </div>

      <div class="input-section" v-show="method === 'post' || method === 'put'">
        <label>请求体（JSON格式，可选）</label>
        <textarea
            v-model="body"
            placeholder="例如：{&quot;title&quot;: &quot;foo&quot;, &quot;body&quot;: &quot;bar&quot;, &quot;userId&quot;: 1}"
            class="body-input"
        ></textarea>
      </div>
    </div>

    <!-- 发送按钮 -->
    <div class="button-group">
      <button @click="sendRequest" :disabled="loading" class="send-button">
        {{ loading ? '发送中...' : '发送请求' }}
      </button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">正在加载...</div>

    <!-- 错误信息 -->
    <div v-if="error" class="error">{{ error }}</div>

    <!-- 响应内容 -->
    <div v-if="response" class="response-section">
      <h3>响应结果：</h3>
      <pre class="response">{{ formattedResponse }}</pre>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'ApiTest',
  data() {
    return {
      method: 'get',
      url: '',
      headers: '',
      body: '',
      response: null,
      error: '',
      loading: false
    };
  },
  computed: {
    // 格式化 JSON 显示
    formattedResponse() {
      try {
        return JSON.stringify(JSON.parse(this.response), null, 2);
      } catch (e) {
        return this.response; // 如果不是 JSON，直接返回原始内容
      }
    }
  },
  methods: {
    async sendRequest() {
      if (!this.url.trim()) {
        this.error = '请输入有效的 URL';
        return;
      }

      this.loading = true;
      this.response = null;
      this.error = '';

      try {
        const config = {};
        if (this.headers.trim()) {
          config.headers = JSON.parse(this.headers);
        }

        let responseData;

        switch (this.method.toLowerCase()) {
          case 'get':
            responseData = await axios.get(this.url, config);
            break;
          case 'post':
            responseData = await axios.post(
                this.url,
                this.body ? JSON.parse(this.body) : {},
                config
            );
            break;
          case 'put':
            responseData = await axios.put(
                this.url,
                this.body ? JSON.parse(this.body) : {},
                config
            );
            break;
          case 'delete':
            responseData = await axios.delete(this.url, config);
            break;
          default:
            throw new Error('不支持的请求方法');
        }

        this.response = JSON.stringify(responseData.data, null, 2);
      } catch (err) {
        this.error = `请求失败：${err.message}`;
        console.error(err);
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>
.api-test-container {
  max-width: 1000px;
  margin: 2rem auto;
  padding: 2rem;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.method-url-group {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.method-select {
  flex: 1;
  padding: 0.75rem;
  font-size: 1rem;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.url-input {
  flex: 3;
  padding: 0.75rem;
  font-size: 1rem;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.input-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1.5rem;
  margin-bottom: 1.5rem;
}

.input-section {
  display: flex;
  flex-direction: column;
}

.input-section label {
  margin-bottom: 0.5rem;
  font-weight: bold;
}

.headers-input,
.body-input {
  height: 120px;
  padding: 0.75rem;
  font-size: 1rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  resize: vertical;
}

.button-group {
  text-align: center;
  margin-bottom: 1.5rem;
}

.send-button {
  padding: 0.75rem 2rem;
  font-size: 1rem;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.send-button:disabled {
  background-color: #aaa;
  cursor: not-allowed;
}

.loading {
  margin-top: 1rem;
  color: #007bff;
  font-weight: bold;
}

.error {
  margin-top: 1rem;
  color: red;
  font-weight: bold;
}

.response-section {
  margin-top: 2rem;
  padding: 1rem;
  background-color: #272822;
  color: #f8f8f2;
  border-radius: 4px;
  overflow-x: auto;
}

.response {
  white-space: pre-wrap;
  font-family: monospace;
}
</style>